package com.uuah.server.transport.provider.mina.codecs.client;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.uuah.server.UuahServer;

/**
 *
 * TODO comment ...
 *
 * <p>
 * update record:updator，update time，update content and version
 * </p>
 *
 * @author <a href="jonny_quan@hotmail.com">jonny</a>
 * @date 2009 2009-3-27 下午02:07:17
 * @version 1.0.0
 */
public class UuahRequestMessageEncoder extends CumulativeProtocolDecoder {
	protected transient Logger logger = LoggerFactory.getLogger(getClass());
	protected CharsetDecoder decoder;

	public UuahRequestMessageEncoder() {
		decoder = Charset.forName(
				UuahServer.getUuahContext().getConfiguration()
						.getDefaultEncoding()).newDecoder();
	}

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("decode");
		}
		int start = in.position();

		byte previous = 0;
		while (in.hasRemaining()) {
			byte current = in.get();

			if (previous == '\r' && current == '\n') {
				int position = in.position();
				int limit = in.limit();
				try {
					in.position(start);
					in.limit(position);
					out.write((in.slice().getString(this.decoder)));
				} finally {
					in.position(position);
					in.limit(limit);
				}
				return true;
			}

			previous = current;
		}
		in.position(start);

		return false;
	}
}
